<?php
/**
 * Created by PhpStorm.
 * User: qingyun
 * Date: 17/2/23
 * Time: 下午3:10
 */
namespace Admin\Controller;
use Common\Controller\AdminBaseController;
use Lib\MyTree;

class GoodsController extends AdminBaseController
{
    public function index()
    {
        $curr = I('get.p/d',0);
        // 获取前端传来的查询词
        $word = I('get.word','');
        $totalNum = 7;
        // 实例化Goods对象
        $goods = D('Goods');
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $field = 'g.id,g.goods_name,b.brand_name,c.classification,g.litimg,g.market_price,g.fd_price,g.number,g.is_integral,g.integral,g.is_sale,g.ret_integral,g.add_time,g.is_boutique,g.is_surprise';
        $join = 'g left join fd_brand b on b.id=g.bid left join fd_classification c on c.id = g.class_id';
        $sqlWhere = empty($word) ? '1=1' : 'g.goods_name like "%'.$word.'%" or b.brand_name like "%'.$word.'%" or c.classification like "%'.$word.'%"';
        $list = $goods->field($field)->join($join)->where($sqlWhere)->page($curr.','.$totalNum)->select();
        // 赋值数据集
        $this->assign('list',$list);
        // 查询满足要求的总记录数
        $count = $goods->join($join)->where($sqlWhere)->count();
        // 实例化分页类 传入总记录数和每页显示的记录数
        $Page  = new \Think\Page($count,$totalNum);
        // 分页显示输出
        $show  = $Page->show();
        $this->assign('word',$word);
        // 赋值分页输出
        $this->assign('page',$show);
        $this->assign('title','FD商城商品表');
        // 输出模板
        $this->display();
    }

    public function add()
    {
        if(IS_AJAX){
            //获取商品名称
            $goods_name = I('post.goods_name','');
            if(empty($goods_name)){
                $this->ajaxReturn(['state'=>1,'msg'=>'商品名不能为空！']);
            }
            //获取商品品牌
            $brand_id = I('post.brand_id/d',0);
            if(empty($brand_id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'请选择商品品牌！']);
            }
            //获取商品品牌
            $classification_id = I('post.classification_id/d',0);
            if(empty($classification_id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'请选择商品类别！']);
            }
            $data = [
                'goods_name'    =>  $goods_name,
                'bid'           =>  $brand_id,
                'class_id'      =>  $classification_id,
                'add_time'      =>  time()
            ];
            //获取是否是积分商品
            $is_integral = I('post.is_integral/d',0);
            if(empty($is_integral)){
                $market_price = I('post.market_price/f',0.00);
                $fd_price = I('post.fd_price/f',0.00);
                $ret_integral = I('post.ret_integral/d',0);
                $data['market_price'] = $market_price;
                $data['fd_price'] = $fd_price;
                $data['ret_integral'] = $ret_integral;
                $data['is_integral'] = 0;
                $data['integral'] = 0;
            }else{
                $data['is_integral'] = $is_integral;
                //获取销售积分
                $data['integral'] = I('post.integral/d',0);
                $data['market_price'] = 0.00;
                $data['fd_price'] = 0.00;
                $data['ret_integral'] = 0;
            }
            //获取简要描述
            $description = I('post.description','');
            if(!empty($description)){
                $data['description'] = $description;
            }
            //获取库存
            $number = I('post.number/d',0);
            if(!empty($number)){
                $data['number'] = $number;
            }
            //获取商品详情
            $body = I('post.body','');
            if(!empty($body)){
                $data['body'] = $body;
            }
            //实例管理员模型
            $goods = D('Goods');
            if($goods->get_field('id',['goods_name'=>$goods_name,'bid'=>$brand_id,'class_id'=>$classification_id])){
                $this->ajaxReturn(['state'=>1,'msg'=>'已经存在此商品！']);
            }
            //获取缩略图路径
            $litimg = I('post.litimg','');
            if(empty($litimg)){
                //如果没有上传图片，直接添加商品信息
                if($goods->add($data)){
                    $this->ajaxReturn(['state'=>0,'msg'=>'添加商品成功！']);
                }
                $this->ajaxReturn(['state'=>1,'msg'=>'添加商品失败！']);
            }
            //开启事务
            $goods->startTrans();
            if(strpos($litimg,',') === false){
                //如果不存在逗号，则是单图片上传
                $data['litimg'] = $litimg;
                $goods_id = $goods->add($data);
                if($goods_id){
                    if(M('Goods_img')->add(['goods_id'=>$goods_id,'litimg'=>$data['litimg']])){
                        //商品信息添加成功并且图片地址储存成功就提交
                        $goods->commit();
                        $this->ajaxReturn(['state'=>0,'msg'=>'添加商品成功！']);
                    }
                    //图片储存失败就回滚
                    $goods->rollback();
                    $this->ajaxReturn(['state'=>1,'msg'=>'商品图片地址储存失败！']);
                }
            }else{
                //如果存在，则是多图片上传
                $goods_img = explode(',',$litimg);
                $data['litimg'] = $goods_img[0];
                $goods_id = $goods->add($data);
                if($goods_id){
                    foreach($goods_img as $v){
                        if(M('goods_img')->add(['goods_id'=>$goods_id,'litimg'=>$v]) == false){
                            //只要有一张图片地址储存失败就回滚
                            $goods->rollback();
                            $this->ajaxReturn(['state'=>1,'msg'=>'商品图片地址储存失败！']);
                        }
                    }
                    //商品信息添加成功并且所有图片地址储存成功就提交
                    $goods->commit();
                    $this->ajaxReturn(['state'=>0,'msg'=>'添加商品成功！']);
                }
            }
            $goods->rollback();
            $this->ajaxReturn(['state'=>1,'msg'=>'添加商品失败！']);
        }else{
            $classification_data = D('classification')->get_many('','id,classification,pid','pid asc');
            $class_tree = new MyTree();
            $classification_info = $class_tree->my_tree($classification_data);
            $this->assign('classification_info',$classification_info);
            $brand_info = D('brand')->get_field('id,brand_name');
            $this->assign('brand_info',$brand_info);
            $this->display();
        }
    }

    public function edit()
    {
        if(IS_POST){
            //获取要修改的商品id
            $id = I('post.id',0);
            if(empty($id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
            }
            //获取商品名称
            $goods_name = I('post.goods_name','');
            if(empty($goods_name)){
                $this->ajaxReturn(['state'=>1,'msg'=>'商品名不能为空！']);
            }
            //获取商品品牌
            $brand_id = I('post.brand_id/d',0);
            if(empty($brand_id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'请选择商品品牌！']);
            }
            //获取商品品牌
            $classification_id = I('post.classification_id/d',0);
            if(empty($classification_id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'请选择商品类别！']);
            }
            $data = [
                'goods_name'    =>  $goods_name,
                'bid'           =>  $brand_id,
                'class_id'      =>  $classification_id,
                'add_time'      =>  time()
            ];
            //获取是否是积分商品
            $is_integral = I('post.is_integral/d',0);
            if(empty($is_integral)){
                //如果不是积分商品则获取市场价、本店价、返积分比例
                $market_price = I('post.market_price/f',0.00);
                $fd_price = I('post.fd_price/f',0.00);
                $ret_integral = I('post.ret_integral/d',0);
                $data['market_price'] = $market_price;
                $data['fd_price'] = $fd_price;
                $data['ret_integral'] = $ret_integral;
                $data['is_integral'] = 0;
                $data['integral'] = 0;
            }else{
                $data['is_integral'] = 1;
                //获取销售积分
                $data['integral'] = I('post.integral/d',0);
                $data['market_price'] = 0.00;
                $data['fd_price'] = 0.00;
                $data['ret_integral'] = 0;
            }
            //获取简要描述
            $description = I('post.description','');
            if(!empty($description)){
                $data['description'] = $description;
            }
            //获取库存
            $number = I('post.number/d',0);
            if(!empty($number)){
                $data['number'] = $number;
            }
            //实例管理员模型
            $goods = D('Goods');
            if(!$goods->get_field('id',['id'=>$id])){
                $this->ajaxReturn(['state'=>1,'msg'=>'不能修改不存在的商品！']);
            }
            if(D('Goods')->where(['id'=>$id])->save($data)){
                $this->ajaxReturn(['state'=>0,'msg'=>'修改商品成功！']);
            }
            $this->ajaxReturn(['state'=>1,'msg'=>'修改商品失败！']);
        }else{
            $id = I('get.id',0);
            if(empty($id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
            }
            $goods_info = D('Goods')->get_one_info(['id'=>$id],'id,goods_name,bid,class_id,market_price,fd_price,number,description,body,is_integral,integral,ret_integral,body');
            $classification_data = D('classification')->get_many('','id,classification,pid','pid asc');
            $class_tree = new MyTree();
            $classification_info = $class_tree->my_tree($classification_data);
            $this->assign('classification_info',$classification_info);
            $brand_info = D('brand')->get_field('id,brand_name');
            $this->assign('brand_info',$brand_info);
            $this->assign('goods_info',$goods_info);
            $this->display();
        }
    }

    public function changeSale()
    {
        if(IS_POST){
            $id = I('post.id/d',0);
            if(empty($id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
            }
            $goods = D('goods');
            $is_sale = $goods->get_field('is_sale',['id'=>$id]);
            if($is_sale === false){
                $this->ajaxReturn(['state'=>1,'msg'=>'修改商品状态失败！']);
            }
            if($is_sale){
                $goods->where(['id' => $id])->setField('is_sale',0);
                $this->ajaxReturn(['state'=>0,'msg'=>'下架此商品成功！','data' => 1]);
            }else{
                $goods->where(['id' => $id])->setField('is_sale',1);
                $this->ajaxReturn(['state'=>0,'msg'=>'上架此商品成功！','data' => 0]);
            }
        }else{
            $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
        }
    }

    public function changeBoutique()
    {
        if(IS_POST){
            $id = I('post.id/d',0);
            if(empty($id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
            }
            $goods = D('goods');
            $is_boutique = $goods->get_field('is_boutique',['id'=>$id]);
            if($is_boutique === false){
                $this->ajaxReturn(['state'=>1,'msg'=>'修改商品状态失败！']);
            }
            if($is_boutique){
                $goods->where(['id' => $id])->setField('is_boutique',0);
                $this->ajaxReturn(['state'=>0,'msg'=>'取消加精成功！','data' => 1]);
            }else{
                $goods->where(['id' => $id])->setField('is_boutique',1);
                $this->ajaxReturn(['state'=>0,'msg'=>'加精成功！','data' => 0]);
            }
        }else{
            $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
        }
    }

    public function changeSurprise()
    {
        if(IS_POST){
            $id = I('post.id/d',0);
            if(empty($id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
            }
            $goods = D('goods');
            $is_surprise = $goods->get_field('is_surprise',['id'=>$id]);
            if($is_surprise === false){
                $this->ajaxReturn(['state'=>1,'msg'=>'修改商品状态失败！']);
            }
            if($is_surprise){
                $goods->where(['id' => $id])->setField('is_surprise',0);
                $this->ajaxReturn(['state'=>0,'msg'=>'成功设置为非惊喜商品！','data' => 1]);
            }else{
                $goods->where(['id' => $id])->setField('is_surprise',1);
                $this->ajaxReturn(['state'=>0,'msg'=>'成功设置为惊喜商品！','data' => 0]);
            }
        }else{
            $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
        }
    }

    public function del()
    {
        if(IS_POST){
            $id = I('post.id/d',0);
            if(empty($id)){
                $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
            }
            $goods = D('Goods');
            $goods_info = $goods->get_one_info(['id'=>$id],'id,litimg');
            if(!$goods_info){
                $this->ajaxReturn(['state'=>1,'msg'=>'不能删除不存在的商品！']);
            }
            //当商品没有图片时直接删除商品
            if(empty($goods_info['litimg'])){
                if($goods->delete($id)){
                    $this->ajaxReturn(['state'=>0,'msg'=>'删除成功！']);
                }
                $this->ajaxReturn(['state'=>1,'msg'=>'删除失败！']);
            }
            //当商品有图片时
            $goods_img = M('goods_img')->where(['goods_id'=>$id])->getField('litimg',true);
            if(empty($goods_img)){
                $this->ajaxReturn(['state'=>1,'msg'=>'发生了未知的错误！']);
            }
            $goods->startTrans();
            if($goods->delete($id) == false || M('goods_img')->where(['goods_id'=>$id])->delete() == false){
                $goods->rollback();
                $this->ajaxReturn(['state'=>1,'msg'=>'删除失败！']);
            }
            foreach($goods_img as $v){
                $img_path = '.'.$v;
                if(is_file($img_path)){
                    unlink($img_path);
                }
            }
            $goods->commit();
            $this->ajaxReturn(['state'=>0,'msg'=>'删除成功！']);
        }else{
            $this->ajaxReturn(['state'=>1,'msg'=>'非法操作！']);
        }
    }

    public function upload_img()
    {
        //储存上传图片
        $config = array(
            'maxSize'    =>    3145728,
            'rootPath'      =>  './Upload/',
            'savePath'   =>    'image/goods_img/',
            'exts'       =>    array('jpg', 'gif', 'png', 'jpeg','bmp'),
            'subName'    =>    array('date','Ymd'),
        );
        // 实例化上传类
        $upload = new \Think\Upload($config);
        $info = $upload -> uploadOne($_FILES['file']);
        if($info) {
            // 上传成功 获取上传文件信息
            $src = '/Upload/'.$info['savepath'].$info['savename'];
            $data = ['state'=>0,'src'=>$src];
        }else{
            // 上传错误提示错误信息
            $err = $upload->getError();
            $data = ['state'=>1,'err'=>$err];
        }
        $this->ajaxReturn($data);
    }
}